package org.yray.sip.factory.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yray.sip.constant.SessionStatusEnum;
import org.yray.sip.factory.IdRuleComponent;
import org.yray.sip.factory.SipServerFactory;
import org.yray.sip.factory.StopWatchFactory;
import org.yray.sip.factory.inet.IMediaFactory;
import org.yray.sip.factory.inet.IRtpReceiver;
import org.yray.sip.factory.inet.IStopWatchFactory;
import org.yray.sip.rtp.sender.FastSender;
import org.yray.sip.rtp.sender.FastSenderCache;
import org.yray.sip.rtp.sender.ISipSessionCache;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;
import org.yray.sip.utils.ByteUtils;
import org.yray.sip.utils.IcspBeanHolder;

@Slf4j
@Component
public class RtpReceiverA implements IRtpReceiver {

    @Autowired
    IMediaFactory iMediaFactory;

    @Autowired
    IdRuleComponent idRuleComponent;
    @Autowired
    SipServerFactory sipServerFactory;
    

    @Override
    public void formatRtp(byte[] bs, SipServerContext ssc, String callId) {
        SipSession sipSession= IcspBeanHolder.getBean(ISipSessionCache.class).get(callId);
        if(sipSession==null||sipSession.getBye().get()) {
            log.info("callId={},has bye,rtp nothing todo",callId);
            return;
        }
        //如果已经转人工了，那就需要把报文转给BLeg
        if(sipSession.getStatus().get() == SessionStatusEnum.TO_MAN_SUCC)
        {
            Long ssrc= ByteUtils.uBytes2IntSip(new byte[]{bs[8],bs[9],bs[10],bs[11]});
            String bId=sipSession.getToManId();
            SipServerContext sipServerContext=sipServerFactory.getSipServerContext(bId);
            SipSession bSipSession=IcspBeanHolder.getBean(ISipSessionCache.class).get(bId);
            FastSender fastSender= FastSenderCache.get(ssrc);
            if(fastSender==null)
            {
               FastSenderCache.put(ssrc,new FastSender(sipServerContext.getUrtpServerHandler().getChannel(),bSipSession.mySideRtpSender()));
            }
            //log.info("toManId={}",bId);
            sipServerContext.getUrtpServerHandler().send(bs,bSipSession.mySideRtpSender());

        }
        else {
            iMediaFactory.addData(ssc.getMediaContext(), bs);
        }
    }
}
